<?php
/**
 * Parent controller for all public controllers
 *
 */
class Admin_Controller extends Zend_Controller_Action
{
    protected $page_type = 'system';
    protected $mobile_detect;

    protected $table_accounts;
    protected $table_roles;
    protected $table_rules;

    protected $table_categories;
    protected $table_objects;
    protected $_table; // current table
    protected $_table_field = 'id_article'; // current field (example 'id_article')

    /**
     * Zend_Auth object
     *
     * @var Zend_Auth
     */
    protected $_auth;
    protected $_user;
    protected $_sess;

    protected $_domain_name;

    protected $_path_real;
    protected $_path_files;
    protected $_path_tmp;
    protected $_path_deamons;
    protected $_path_lang_messages;

    protected $_files; // Llib_Files Object
    protected $_tumb;  // Tumb_images Object
    protected $_http_files;

    protected $controller;
    protected $action;

    protected $_menu;
    protected $active_cat = 87; // Active current cat at menu // Root page as default
    protected $active_cat_root = 87; // Root page as default
    protected $active_cat_parent = 0; // Parent of active cat

    protected $root_admin_cat = 87;  // root id fo admin menu - const
    protected $root_client_cat = 62;  // root id fo client menu - const

    protected $max_folders_count = 100000; // Const, root of struct menu

    protected $_lang = 'ru'; // Constant

    /**
     * Method starts when controller startup
     *
     */
    public function init()
    {
    	$this->controller = $this->getRequest()->getControllerName();
    	$this->action = $this->getRequest()->getActionName();

    	$this->_sess = new Zend_Session_Namespace($this->controller.'/'.$this->action);
    	$this->_auth = Zend_Registry::get('auth');
        $this->_user = $this->_auth->getIdentity();

        $this->_domain_name = Zend_Registry::get('config')->domains->front;

        $this->_path_real =  realpath( dirname(dirname(dirname(__FILE__))));
        $this->_path_files = $this->_path_real.'/portal/files';
        $this->_path_tmp = $this->_path_files.'/tmp';
        $this->_path_deamons = $this->_path_real.'/deamons';
        $this->_path_lang_messages = $this->_path_real.'/languages/messages.tmx';
        $this->_http_files = 'http://'.Zend_Registry::get('config')->domains->files;

        $this->_files = new Llib_Files($this->_path_files);

        $this->table_accounts = new Admin_Table_Accounts();
        $this->table_roles = new Admin_Table_Role();
        $this->table_rules = new Admin_Table_Rule();

        $this->table_categories  = new Admin_Table_Categories();
        $this->table_objects = new Admin_Table_Objects();
        $this->mobile_detect = new MobileDetect();

        $this->InitMenu();
        $this->_initView();
    }

    /**
     * Method initialization of view valiables
     *
     */
    protected  function _initView()
    {
        $detect = new MobileDetect();
        
        $this->view->Settings('path', Zend_Registry::get('config')->base_url);
        $this->view->Settings('site_url', Zend_Registry::get('config')->site_url);

        $this->view->Settings('title', Zend_Registry::get('config')->title);

        $this->view->Settings('url', 'http://'.Zend_Registry::get('config')->domains->admin);
        $this->view->Settings('files_url', 'http://'.Zend_Registry::get('config')->domains->files);
        $this->view->Settings('images_url', 'http://'.Zend_Registry::get('config')->domains->admin.'/images');
        $this->view->Settings('main_url', 'http://'.Zend_Registry::get('config')->domains->front);
        
        //Settings data added to xml
        $this->view->Settings('user_agent', $_SERVER['HTTP_USER_AGENT']);
        $this->view->Settings('controller', $this->controller);
        $this->view->Settings('action', $this->action);
        $this->view->Settings('website_name', Zend_Registry::get('config')->website_name);

        $this->view->Settings('this', $this->getRequest()->getServer('REDIRECT_URL'));
        $this->view->Settings('is_mobile', $this->mobile_detect->isMobile() || $this->mobile_detect->isTablet());
       // $this->view->Settings('is_mobile','1');
    }



    /**
     * Start content tag in result xml
     *
     */

    protected function startContent()
    {
        $this->view->xmlWriter->startElement('content');
        if (!is_null($this->active_cat))$this->view->xmlWriter->writeAttribute('cat', $this->active_cat);
        if (!is_null($this->page_type))$this->view->xmlWriter->writeAttribute('pagetype', $this->page_type);
        if (!is_null($this->page_type))$this->view->xmlWriter->writeAttribute('table_field', $this->_table_field);
        $this->_content();
    }

    /**
     * Method, for generation xml content in parent controller
     *
     */
    protected function _content()
    {
    	$currTime = time();

        $use_png_filtered = (strpos($this->getRequest()->getServer('HTTP_USER_AGENT'), 'MSIE') !== false)?(1):(0);
        $this->view->Settings('browser', array('use_png_filtered'=>$use_png_filtered));
        $current_date['current-date']['__attributes'] = Apk_Util::timestampToArray(time());
        $this->view->assign($current_date);

        if($this->_auth->hasIdentity())
        {
            $this->view->assign('Path', $this->GetMenuPath());

            $cats = $this->GetMenu();
            $this->view->xmlWriter->startElement("Cats");
            $this->view->xmlWriter->writeAttribute('root', $this->active_cat_root);
            $this->view->xmlWriter->writeAttribute('parent', $this->active_cat_parent);
            $this->view->assign($cats);
            $this->view->xmlWriter->endElement();
        }

    	// Authorization information
        $this->view->xmlWriter->startElement("auth-info");
    	$this->view->assign('hasIdentity', intval($this->_auth->hasIdentity()));
    	//$this->view->assign('perm', $this->getPerm());

    	if($this->_auth->hasIdentity())
    	{
    		$this->view->assign('id', $this->_user->id);
    		$this->view->assign('name', $this->_user->first_name);
    		$this->view->assign('email', $this->_user->email);
    		$this->view->assign('role_id', $this->_user->role_id);
                $this->view->assign('koatuu', $this->_user->koatuu);
    	}
    	else
    	{
    		$this->view->assign('name', 'guest');
    	}
    	$this->view->xmlWriter->endElement();

    }

    /**
     *Find element def in not_def by name
     *
     * @param array $not_def
     * @param array $def
     * @return  key or false if not found
     */

    protected static function _findnotDefault($def,$not_def)
    {
        foreach ($not_def as $key => $val){
            if (  $val['name'] == $def['name']) return $key;
        }
        return false;
    }

    /**
     * Close content tag in result xml.
     *
     */
    protected function endContent()
    {
        $this->view->xmlWriter->endElement();
    }


    public function getFileAdapter()
    {
    	$adapter = new Zend_File_Transfer_Adapter_Http();
    	$adapter->setOptions(array('ignoreNoFile'=>1));
    	$adapter->addValidator('Size', false, array('min' => 0, 'max' => 6000000));
    	$adapter->addValidator('Extension', false, array('jpg', 'png', 'gif', 'case' => false));
    	$adapter->setDestination($this->_path_tmp);

    	$this->createTumbAdapter();
    	return $adapter;
    }

    public function getFileAdapterAll()
    {
    	$adapter = new Zend_File_Transfer_Adapter_Http();
    	$adapter->setOptions(array('ignoreNoFile'=>1));
    	$adapter->addValidator('Size', false, array('min' => 0, 'max' => 1000000000));
    	//$adapter->addValidator('Extension', false, array('jpg', 'png', 'gif','avi', 'mov', 'flv', 'jpeg','mp4','mpg', 'txt', 'case' => false));

    	try{
    		$adapter->setDestination($this->_path_tmp);
    	}catch (Exception $e)
    	{
    		echo $this->_path_tmp.'<br>';
    		echo $e->__toString();
    		die();
    	}

    	$this->createTumbAdapter();
    	return $adapter;
    }

    public function createTumbAdapter()
    {
    	require_once 'Tumb/ThumbLib.inc.php';
    	$this->_tumb = new PhpThumbFactory;
    }

	// load file
	public function LoadFile($id, &$form, &$d, $controller = null)
	{
	    $k = 100000;
		if(is_null($controller)) $controller = $this->controller;

		$this->_files->CreateFolder('/'.$controller);
        $adapter = $this->getFileAdapterAll();

    	$this->_files->CreateFolder(intval($id/$k), '/'.$controller);
    	$this->_files->CreateFolder($id, '/'.$controller.'/'.intval($id/$k));
    	//if($_FILES['avatar']['name'] != '') $this->_files->EmptyFolder('/'.$controller.'/'.intval($id/$k).'/'.$id);

    	$path = '/'.$controller.'/'.intval($id/$k).'/'.$id.'/';
    	$adapter->setDestination($this->_path_files.$path);

        if ($adapter->receive()) {
    		$files = $adapter->getFileInfo();
    		$file = $files['attache'];

    		if(!(isset($file['name']) && trim($file['name']) != '')) return 0;

			$f_arr = explode('.', $file['name']);

			if(count($f_arr) > 1) $file_name = $id.'.'.$f_arr[count($f_arr) - 1];
			else $id.'.0';

        	rename($this->_path_files.$path.$file['name'], $this->_path_files.$path.$file_name);

        	$d['file_name_var'] = $file_name;
			$d['file_size'] = $file['size'];
    		//$d['path_var'] = $path;
    		$d['path'] = $path;
    		//$d['process'] = 1;
    	}
    	else
    	{
		    $messages = $adapter->getMessages();
		    $errors = $adapter->getErrors();
		    $form->SetError(implode("\n", $messages).implode("\n", $errors));
    	}

    	return 0;
	}


	public function LoadObject($id, &$form, $field = 'id_gallery', $controller = 'objects', &$id_object = 0, $user_id = 0, &$image = array())
	{
	    $k = $this->max_folders_count;
		if(is_null($controller)) $controller = $this->controller;

		$this->_files->CreateFolder('/'.$controller);
        $adapter = $this->getFileAdapter();

        //print_r($adapter); die();

        if ($adapter->receive()) {
			$files = $adapter->getFileInfo();
			$file = $files['Filedata'];

			$id_object = $this->table_objects->insert(array($field => $id), $user_id);

	    	$this->_files->CreateFolder(intval($id_object/$k), '/'.$controller);
	    	$this->_files->CreateFolder($id_object, '/'.$controller.'/'.intval($id/$k));
	    	$path = '/'.$controller.'/'.intval($id_object/$k).'/'.$id_object.'/';

			$image = $this->LoadImage($file, $path, $id_object, $controller, true, true);
			$this->table_objects->update($image, $id_object, $user_id);
    	}
    	else
    	{
		    $messages = $adapter->getMessages();
		    $errors = $adapter->getErrors();
		    if(is_object($form))  $form->SetError(implode("\n", $messages).implode("\n", $errors));
		    else echo implode("\n", $messages).implode("\n", $errors);
    	}


    	return 1;
	}

	public function LoadAvatar($id, &$form, &$d, $controller = null)
	{
	    $k = $this->max_folders_count;
		if(is_null($controller)) $controller = $this->controller;

		$this->_files->CreateFolder('/'.$controller);
        $adapter = $this->getFileAdapter();

    	$this->_files->CreateFolder(intval($id/$k), '/'.$controller);
    	$this->_files->CreateFolder($id, '/'.$controller.'/'.intval($id/$k));
    	if($_FILES['avatar']['name'] != '') $this->_files->EmptyFolder('/'.$controller.'/'.intval($id/$k).'/'.$id);

    	$path = '/'.$controller.'/'.intval($id/$k).'/'.$id.'/';
    	$adapter->setDestination($this->_path_files.$path);

        if ($adapter->receive()) {
    		$files = $adapter->getFileInfo();

    		$image = $this->LoadImage($files['avatar'], $path, $id, $controller);
    		$d = array_merge($d, $image);
    	}
    	else
    	{
		    $messages = $adapter->getMessages();
		    $errors = $adapter->getErrors();
		    $form->SetError(implode("\n", $messages).implode("\n", $errors));
    	}

    	return 0;
	}

    /**
     * Load image with diff sizes
     *
     * @param array $file - loaded image file
     * @param string $path - /controller/id/
     * @param array $data - old loaded data
     *
     * @return data for updates
     */

    public function LoadImage($file, $path, $id, $controller = null, $is_tmp = false, $is_exif = false)
    {
    	if(!($file['error'] == 0 && (
    		   $file['type'] == 'image/jpeg'
    		|| $file['type'] == 'application/octet-stream'
    		|| $file['type'] == 'image/png'
    		|| $file['type'] == 'image/gif')
    	)) return array();


    	if(trim($path) == '') return array();
    	if(!($id > 0)) return array();

    	require_once 'Tumb/ThumbLib.inc.php';

    	if(is_null($controller)) $sizes = Zend_Registry::get('config')->images->modules->{$this->controller}->toArray();
    	else $sizes = Zend_Registry::get('config')->images->modules->{$controller}->toArray();
    	$d = array();

    	if($is_tmp)
    	{
    		copy($this->_path_tmp.'/'.$file['name'], $this->_path_files.$path.$file['name']);
    		$this->_files->RemoveFile('/tmp/'.$file['name']);
    	}

    	if($is_exif)
    	{
    		$exif = exif_read_data($this->_path_files.$path.$file['name']);

    		$d['exif_Make'] = @$exif['Make'];
    		$d['exif_Model'] = @$exif['Model'];
    		$d['exif_Orientation'] = @$exif['Orientation'];
    		$d['exif_XResolution'] = @$exif['XResolution'];
    		$d['exif_YResolution'] = @$exif['YResolution'];
			$d['exif_ResolutionUnit'] = @$exif['ResolutionUnit'];
			$d['exif_DateTime'] = @$exif['DateTime'];
			$d['exif_YCbCrPositioning'] = @$exif['YCbCrPositioning'];
			$d['exif_Software'] = @$exif['Software'];
			$d['exif_ExposureTime'] = @$exif['ExposureTime'];
			$d['exif_FNumber'] = @$exif['FNumber'];
			$d['exif_ISOSpeedRatings'] = @$exif['ISOSpeedRatings'];


			if(trim($d['exif_DateTime']) != '')
			{
				$arr_date = explode(':', $d['exif_DateTime']);
				$arr_date2 = explode(' ', $arr_date[2]);
				if(count($arr_date) == 5)
					$dateInt = mktime($arr_date2[1],$arr_date[3],$arr_date[4],$arr_date[1],$arr_date2[0], $arr_date[0]);
				else $dateInt = time();
			}else $dateInt = time();

			$d['exif_DateTimeInt'] = $dateInt;
			$d['norder'] = time();
    	}


    	//$this->WaterMark($this->_path_files.$path.$file['name']);

    	switch($file['type'])
    	{
    		case 'image/gif':
    			$file_name = time().'.gif';
    			break;
    		case 'image/png':
    			$file_name = time().'.png';
    			break;
    		default:
    			$file_name = time().'.jpg';
    	}

    	rename($this->_path_files.$path.$file['name'], $this->_path_files.$path.$file_name);

    	foreach($sizes as $type => $size)
    	{
    			$thumb = $this->_tumb->create($this->_path_files.$path.$file_name);

    			switch($size['type'])
				{
					case 'Strict':
						$thumb->adaptiveResize($size['width'], $size['height']);
						break;
					default:
						$thumb->resize($size['width'], $size['height']);
						break;
				}

				try{
	    			$thumb->save($this->_path_files.$path.($id.$type.$file_name));
				}catch(Exeption $e)
				{
					echo $e->__toString();
					die();
				}
    	}

   		$d['file_name'] = $file_name;
		$d['path'] = $path;


		if($controller == 'objects')	{
			$d['title_ru'] = $file['name'];
			$d['title_ua'] = $file['name'];
		}

		unlink($this->_path_files.$path.$file_name);

		return $d;
    }

public function CropImage($id, $path, $file_name, $coords, $controller = null, $type = 'avatar', $is_change_other = true)
    {
    	if(trim($path) == '') return array();
    	if(!($id > 0)) return array();

    	require_once 'Tumb/ThumbLib.inc.php';
    	$adapter = $this->getFileAdapter();



    	if(is_null($controller)) $sizes = Zend_Registry::get('config')->images->modules->{$this->controller}->toArray();
    	else $sizes = Zend_Registry::get('config')->images->modules->{$controller}->toArray();

        $thumb = $this->_tumb->create($this->_path_files.$path.$id.'original'.$file_name);


        $thumb->crop($coords['x'], $coords['y'], $coords['w'], $coords['h']);
        $thumb->adaptiveResize($sizes[$type]['width'], $sizes[$type]['height']);
        $thumb->save($this->_path_files.$path.($id.$type.$file_name));

        if($is_change_other)
        foreach($sizes as $t => $size)
    	{
    		if($size['type'] == $type || $size['type'] == 'original') continue;

    	    $thumb = $this->_tumb->create($this->_path_files.$path.($id.$type.$file_name));

    			switch($size['type'])
				{
					case 'Strict':
						$thumb->adaptiveResize($size['width'], $size['height']);
						break;
					default:
						$thumb->resize($size['width'], $size['height']);
						break;
				}

	    		$thumb->save($this->_path_files.$path.($id.$t.$file_name));
    	}

		return true;
    }

    public function setActiveCat($id)
    {
    	$this->active_cat = $id;
    }


    public function SessionVars($data, $vars = array(), $rest = 0)
    {
    	$ret = array();
    	if($rest != ''){
    		foreach($vars as $var)
    		{
    			switch($var)
    			{
    				case 's':
    				case 'search_text':
    					$this->_sess->{$var} = '';
    					break;
    				case 'id_cat_view':
    					$this->_sess->{$var} = 1;
    					break;
    				default:
    				   $this->_sess->{$var} = -1;
    			}
    			$ret[$var] = $this->_sess->{$var};
    		}

    		return $ret;
    	}

        foreach($data as $k=>$v)
    	{
    		switch($k)
    		{
    			case 'search_text':
    			case 's':
    				$this->_sess->{$k} = $v;
    				break;
    			default:
    				if(isset($v) && $v !== '')
    					$this->_sess->{$k} = $v;
    		}
    	}

    	foreach($vars as $var)
    		$ret[$var] = $this->_sess->{$var};

    	return $ret;
    }
    
public function SessionVarsEx($data, $vars = array(), $reset = false) {
        $result = array();

        if (!empty($reset)) {
            foreach ($vars as $key => $value) {
                if (is_string($key)) {
                    $this->_sess->{$key} = $value;
                    $result[$key] = $this->_sess->{$key};
                } else {
                    $this->_sess->{$value} = '';
                    $result[$value] = $this->_sess->{$value};
                }
            }
            return $result;
        }

        foreach ($data as $key => $value) {
            if (isset($value)) {
                $this->_sess->{$key} = $value;
            }
        }

        foreach ($vars as $key => $value) {
            if (is_string($key)) {
                if (!isset($this->_sess->{$key})) {
                    $this->_sess->{$key} = $value;
                }
                $result[$key] = $this->_sess->{$key};
            } else {
                if (!isset($this->_sess->{$value})) {
                    $this->_sess->{$value} = '';
                }
                $result[$value] = $this->_sess->{$value};
            }
        }

        return $result;
    }


    //****************************************
    // Menu functions
    //****************************************

    private function InitMenu()
    {
		$params = array(
			'id' => 'id',
			'idt' => 'idt',
			'root_id' => 'rootid',
			'id_type' => 'id_type',
			'id_menu' => 'id_menu',
			'site' => 'site',
			'controller' => 'controller',
	    	'l' => 'l',
		    'r' => 'r',
		    'norder' => 'norder',
		    'level' => 'level',
	    	'parent_id'=>'parent',
	    	'menu_name_ru' => 'menu_name_ru',
	    	'menu_name_ua' => 'menu_name_ua',
	    	'menu_name_en' => 'menu_name_en',
	    	'title_ru' => 'title_ru',
	    	'title_ua' => 'title_ua',
	    	'title_en' => 'title_en',
	    	'url' => 'url',
	    	'is_active' => 'is_active',
	    	'text_ru' => 'text_ru',
	    	'text_ua' => 'text_ua',
	    	'text_en' => 'text_en',
	    	'add_date' => 'add_date',
	    	'modify_date' => 'modify_date',
	    	'is_community' => 'is_community',
			'path' => 'path',
			'file_name' => 'file_name'
	    );

	    $this->_menu =& DB_NestedSet::factory('DBLite', NULL, $params);
	    $this->_menu->factory('DBLite', NULL, $params);
	    $this->_menu->setAttr(array(  'node_table' => 'categories'));
    }

    private function GetMenuPath()
    {
 		$element = $this->_menu->pickNode($this->active_cat, true);
    	$parents = $this->_menu->getParents($this->active_cat);
 		$path = array();
 		$i=0;
 		if (sizeof($parents)) {
 			foreach($parents as $parent){
     			if($i>0){
     					$path[$i]['id'] = $parent->id;
    					$path[$i]['name'] = $parent->menu_name_ru;
    					$path[$i]['url'] = $parent->url;
     			}
     			$i++;
 			}
 		}

 		$path[$i]['id'] = $element['id'];
 		$path[$i]['name'] = $element['menu_name_ru'];
 		$path[$i]['url'] = $element['url'];

 		return $path;
    }

    private function GetMenu()
    {

    	$parents = $this->_menu->getParents($this->active_cat);
 		$data = array();
 		if (sizeof($parents)) {
 			foreach($parents as $parent) {
 					$data[] = $parent->id;
 			}
 		}
 		$data[] = $this->active_cat;
 		//$this->active_cat_root = $data[2];
 		//$this->active_cat_parent = $data[count($data)-2];
 		//return $this->table_admin_cats->GetMenu($data);

 		return $this->table_categories->GetChildList($this->root_admin_cat, $data, null, $this->_user->role_name);
    }

    // Actions default

    public function addAction()
    {
		$id = $this->_table->insert(array(), $this->_user->id);
		if($id > 0)
		{
			$this->_redirect('/'.$this->controller.'/edit/'.$id);
		}else $this->_redirect('/error/e404');
    }

    public function removeAction()
    {
    	$form = new Llib_Form($this->_request);
    	$d = $form->GetPostedData();

    	if(count($d['selected_id']) > 0) $this->_table->remove($d['selected_id'], $this->_user->id);
    	$this->_redirect('/'.$this->controller);
    }

    public function removeOneAction()
    {
    	$id = $this->_getParam('id');
    	if($id > 0) $this->_table->remove(array($id), $this->_user->id);
    	$this->_redirect('/'.$this->controller);
    }

    public function uploadphotosAction()
    {
    	$id = $this->_getParam('id');
    	$field = $this->_getParam('f', 'id_article');
    	$data = $this->_table->GetDataRow($id);

 		$this->LoadObject($id, $form, $field, 'objects', $id_object, $data['add_user_id'], $image);

		echo $this->_http_files.$image['path'].$id_object.'square_small'.$image['file_name'];
		echo '::';
		echo $this->_http_files.$image['path'].$id_object.'avatar_small'.$image['file_name'];
		$this->_table->photo_count($id);
    	die();
    }

	public function uploadAvatarAction()
    {
    	$id = $this->_getParam('id', 0);
    	if(!($id > 0)) die('ERROR:uploadphotosAction: id = '.$id);

    	$form = new Llib_Form($this->_request);
        $d = array();

        $this->LoadAvatar($id, $form, $d, $this->controller);
        $this->_table->update_all($d, $id, $id);
		echo $this->_http_files.$d['path'].$id.'avatar'.$d['file_name'];

    	die();
    }

	public function removeAvatarAction()
    {
    	$id = $this->_getParam('id', 0);
    	if(!($id > 0)) die('ERROR:removeAvatarAction: id = '.$id);

    	$form = new Llib_Form($this->_request);

        $d = array();

        $d['path'] = '';
        $d['file_name'] = '';

        $this->_table->update_all($d, $id, $id);
    	die('OK');
    }

	public function ajaxOrderPhotoAction()
    {
    	$id = $this->_request->getParam('id');
    	$norder = $this->_request->getParam('norder');
    	$old = $this->_request->getParam('old');
    	$f = $this->_request->getParam('f', 'id_article');

    	$params[$f] = $this->_request->getParam('cat');
    	if(!($id > 0)) die('ERROR');

    	$this->table_objects->OrderNumber($id, $norder, $old, $params);
    	die('OK');
    }

    public function exifOrderAction()
    {
    	$id = $this->_request->getParam('id');
    	$f = $this->_request->getParam('f', 'id_article');
    	if(!($id > 0)) $this->_redirect('/error/e404');

    	$this->table_objects->order_exif($id, $f);

    	$this->_redirect('/'.$this->controller.'/photos/'.$id);
    }

    public function adddateOrderAction()
    {
    	$id = $this->_request->getParam('id');
    	$f = $this->_request->getParam('f', 'id_article');
    	if(!($id > 0)) $this->_redirect('/error/e404');

    	$this->table_objects->order_adddate($id, $f);

    	$this->_redirect('/'.$this->controller.'/photos/'.$id);
    }

    public function removephotoAction()
    {
    	$gid = $this->_request->getParam('gid');
    	if(!($gid > 0)) $this->_redirect('/error/e404');

    	$form = new Llib_Form($this->_request);
    	$d = $form->GetPostedData();

    	if(count($d['selected_id']) > 0){
    		$this->table_objects->remove($d['selected_id'], $this->_user->id);
    		$this->_table->photo_count($gid);
    	}
    	$this->_redirect('/'.$this->controller.'/photo/id/'.$gid);
    }

    public function refreshIdtAction()
    {
        $title = $this->_getParam('title');
        echo $this->tstring($title);
        die();
    }
    
	public function cleanCache()
    {
    	$this->_files->SetRootPath($this->_path_real);
		$this->_files->level_access = 2;

    	if(!$this->_files->EmptyFolder('/admin_cache'))  die('error:'.$this->_files->GetError());
    	if(!$this->_files->EmptyFolder('/client_cache'))  die('error:'.$this->_files->GetError());
    }
    
    public function is_mobile(){
        
    }

    public function ajaxOut($output = '', $type = 'html')
    {
    	 if($type == 'json') $output = Zend_Json::encode($output);
    	 Zend_Controller_Action_HelperBroker::removeHelper('viewRenderer');
         $response = $this->getResponse();
         $response->setBody($output)->setHeader('content-type', 'application/'.$type, true);
	}

    public function cropAction()
    {
        $id = $this->_request->getParam('id');
    	if(!($id > 0)) die();

        $coords['x'] = $this->_getParam('x', 0);
        $coords['y'] = $this->_getParam('y', 0);
        $coords['w'] = $this->_getParam('w', 0);
        $coords['h'] = $this->_getParam('h', 0);

        $d = $this->_table->GetDataRow($id);

        $this->CropImage($id, $d['path'], $d['file_name'], $coords, $this->controller, 'avatar', false);

        die('OK');
    }


    //****************************************
    // Staff function
    //****************************************
    public function MakeSeed() {
	    list($usec, $sec) = explode(' ', microtime());
	    return (float) $sec + ((float) $usec * 100000);
	}

	public function tstring($inputStr)
  	{
  		$t = array(
  				"а" => "a", "б" => "b", "в" => "v", "г" => "g",
  				"д" => "d", "е" => "e", "ё" => "e", "ж" => "zh",
  				"з" => "z", "и" => "i", "й" => "y", "к" => "k",
  				"л" => "l", "м" => "m", "н" => "n", "о" => "o",
  				"п" => "p", "р" => "r", "с" => "s", "т" => "t",
  				"у" => "u", "ф" => "f", "х" => "h", "ц" => "ts",
  				"ч" => "ch", "ш" => "sh", "щ" => "shch", "ъ" => "",
  				"ь" => "", "э" => "ie", "ю" => "yu", "я" => "ya",
  				"ї" => "yi", "і" => "i", " " => "-", "-" => "-", "ы" => "i",
  				"ö" => "o", "є" => "e",

  				"А" => "a", "Б" => "b", "В" => "v", "Г" => "g",
  				"Д" => "d", "Е" => "e", "Ё" => "e", "Ж" => "zh",
  				"З" => "z", "И" => "i", "Й" => "y", "К" => "k",
  				"Л" => "l", "М" => "m", "Н" => "n", "О" => "o",
  				"П" => "p", "Р" => "r", "С" => "s", "Т" => "t",
  				"У" => "u", "Ф" => "f", "Х" => "h", "Ц" => "ts",
  				"Ч" => "ch", "Ш" => "sh", "Щ" => "shch", "Ъ" => "",
  				"Ь" => "", "Э" => "ie", "Ю" => "yu", "Я" => "ya",
  				"Ї" => "yi", "І" => "i", "Ы" => "I",

  				"0" => "0", "1" => "1", "2" => "2", "3" => "3",
  				"4" => "4", "5" => "5", "6" => "6", "7" => "7",
  				"8" => "8", "9" => "9",

  				"a" => "a", "b" => "b", "c" => "c", "d" => "d",
  				"e" => "e", "f" => "f", "g" => "g", "h" => "h",
  				"i" => "i", "j" => "j", "k" => "k", "l" => "l",
  				"m" => "m", "n" => "n", "o" => "o", "p" => "p",
  				"q" => "q", "r" => "r", "s" => "s", "t" => "t",
  				"u" => "u", "v" => "v", "w" => "w", "x" => "x",
  				"y" => "y", "z" => "z",

  				"A" => "a", "B" => "b", "C" => "c", "D" => "d",
  				"E" => "e", "F" => "f", "G" => "g", "H" => "h",
  				"I" => "i", "J" => "j", "K" => "k", "L" => "l",
  				"M" => "m", "N" => "n", "O" => "o", "P" => "p",
  				"Q" => "q", "R" => "r", "S" => "s", "T" => "t",
  				"U" => "u", "V" => "v", "W" => "w", "X" => "x",
  				"Y" => "y", "Z" => "z"
  		);

  		$inputStrLength = mb_strlen(strtolower(trim($inputStr)));
  		$translated = '';

  		for($i = 0; $i < $inputStrLength; $i++) {
  			$currentChar = mb_substr($inputStr, $i, 1);
  			if(isset($t[$currentChar]))
  				$translated .= $t[$currentChar];
  		}

    	return $translated;
  }
}
